package com.hualan.utils;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


public class ExecUtil {
    private static PreparedStatement preparedStatement;
    private static Connection conn;
    public static Object execute(String sql, List<Object> params, HttpServletRequest req ,Boolean update) {
        conn = (Connection) req.getAttribute("conn");
        try {
            preparedStatement = conn.prepareStatement(sql);

            for (Integer i = 0; i < params.size(); i++) {
                preparedStatement.setObject(i + 1, params.get(i));
            }
            if (update) {
                preparedStatement.executeUpdate();
                return true;
            } else {
                ResultSet exec = preparedStatement.executeQuery();
                return exec;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void close()  {
        try {
            preparedStatement.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void commit(){
        try {
            conn.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void rollback(){
        try {
            conn.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
